package com.shang.controller.center;

import com.shang.controller.BaseController;
import com.shang.pojo.Users;
import com.shang.pojo.bo.center.CenterUsersBO;
import com.shang.pojo.vo.UsersVO;
import com.shang.resource.FileUpload;
import com.shang.service.center.CenterUserService;
import com.shang.utils.CookieUtils;
import com.shang.utils.DateUtil;
import com.shang.utils.JsonUtils;
import com.shang.utils.ShangJSONResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value = "用户信息接口")
@RestController
@RequestMapping("userInfo")
public class CenterUserController extends BaseController{

    @Autowired
    private CenterUserService centerUserService;

    @Autowired
    private FileUpload fileUpload;


    @ApiOperation(value = "修改用户头像")
    @PostMapping("uploadFace")
    public ShangJSONResult uploadFace(@RequestParam String userId, MultipartFile file,HttpServletRequest request, HttpServletResponse response){

//        String fileSpace = IMAGE_USER_FACE_LOCATION;
        String fileSpace = fileUpload.getImageUserFaceLocation();
        String uploadPathPrefix = File.separator + userId;
        if (file != null){
            FileOutputStream fileOutputStream = null;
            try {
                String filename = file.getOriginalFilename();
                if (StringUtils.isNoneBlank(filename)){
                    String[] fileNameArr = filename.split("\\.");
                    //文件后缀名
                    String suffix = fileNameArr[fileNameArr.length - 1];
                    if (!suffix.equalsIgnoreCase("png") && !suffix.equalsIgnoreCase("jpg") && !suffix.equalsIgnoreCase("jpeg")){
                        return ShangJSONResult.errorMsg("图片格式不正确");
                    }
                    String newFileName = "face-" + userId + "." + suffix;

                    String finalFacePath = fileSpace + uploadPathPrefix + File.separator + newFileName;

                    uploadPathPrefix += ("/" + newFileName);

                    File outFile = new File(finalFacePath);
                    if (outFile.getParentFile() != null){
                        outFile.getParentFile().mkdirs();
                    }

                    //文件输出 保存到目录
                    fileOutputStream = new FileOutputStream(outFile);
                    InputStream inputStream = file.getInputStream();
                    IOUtils.copy(inputStream,fileOutputStream);
                }
            }catch (IOException e){
                e.printStackTrace();
            }finally {
                if (fileOutputStream != null){
                    try {
                        fileOutputStream.flush();
                        fileOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }else {
            return ShangJSONResult.errorMsg("文件不能为空");
        }
        String imageServerUrl = fileUpload.getImageServerUrl();
        String finalUserFaceUrl = imageServerUrl + uploadPathPrefix + "?t=" + DateUtil.getCurrentDateString(DateUtil.DATE_PATTERN);
        //更新头像到数据库
        Users userResult = centerUserService.updateUserFace(userId, finalUserFaceUrl);

//        userResult = setNullProperty(userResult);
        UsersVO usersVO = conventUsersVO(userResult);

        CookieUtils.setCookie(request,response,"user", JsonUtils.objectToJson(usersVO),true);
        return ShangJSONResult.ok();
    }


    @ApiOperation(value = "修改用户信息")
    @PostMapping("update")
    public ShangJSONResult update(@RequestParam String userId, @RequestBody @Valid CenterUsersBO centerUsersBO, BindingResult result, HttpServletRequest request, HttpServletResponse response){

        if (result.hasErrors()){
            Map<String, String> map = getErrors(result);
            return ShangJSONResult.errorMap(map);
        }

        Users userResult = centerUserService.updateUserInfo(userId, centerUsersBO);
//        userResult = setNullProperty(userResult);
        UsersVO usersVO = conventUsersVO(userResult);

        CookieUtils.setCookie(request,response,"user", JsonUtils.objectToJson(usersVO),true);
        return ShangJSONResult.ok(userResult);
    }


    private Map<String,String> getErrors(BindingResult result){
        Map<String,String> map = new HashMap<>();
        List<FieldError> errorList = result.getFieldErrors();
        for (FieldError error : errorList){
            String errorField = error.getField();
            String errorMsg = error.getDefaultMessage();
            map.put(errorField,errorMsg);
        }
        return map;
    }

    private Users setNullProperty(Users users){
        users.setPassword(null);
        users.setMobile(null);
        users.setEmail(null);
        users.setCreatedTime(null);
        users.setUpdatedTime(null);
        users.setBirthday(null);

        return users;

    }

}
